package CelestialWeb;

import CelestialDataAccess.Customer;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
import java.net.URLEncoder;

import CelestialDataAccess.*;
import CelestialWorkflow.*;
import CelestialDataStructures.*;

public class AccountServlet extends HttpServlet {
   
    AccountControl m_AccountControl = new AccountControl();
    WriteXMLError m_WriteError = new WriteXMLError();

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        String strAction = request.getParameter("action");

        if(strAction.compareTo("register")==0)
            registerCustomer(request, response);
        
        if(strAction.compareTo("get")==0)
            getCustomer(request, response);
        
        else if(strAction.compareTo("post")==0)
            updateCustomer(request, response);

        else if (strAction.compareTo("v_email") == 0)
            validateEmail(request, response);

        else if(strAction.compareTo("v_contact")==0)
            validateContact(request, response);

        else if(strAction.compareTo("v_cc_num")==0)
            validateCreditCardNumber(request, response);

        else if(strAction.compareTo("v_cc_issuer")==0)
            validateCreditCardIssuer(request, response);

        else if(strAction.compareTo("v_cc_expiry")==0)
            validateCreditCardExpiry(request, response);

        else if(strAction.compareTo("v_fst_name")==0)
            validateFirstName(request, response);

        else if(strAction.compareTo("v_lst_name")==0)
            validateLastName(request, response);

        else if(strAction.compareTo("v_dob")==0)
            validateDOB(request, response);
        
        else if(strAction.compareTo("v_retype_pw")==0)
            validateRetypePassword(request, response);

        else if(strAction.compareTo("change_cc")==0)
            changeCreditCard(request, response);

        else if(strAction.compareTo("change_pw")==0)
            changePassword(request, response);

        else if(strAction.compareTo("pw_strength")==0)
               getPasswordStrength(request, response);
        
        else return;
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    /*************************************************************************/
    /* Helpers */
    /*-----------------------------------------------------------------------*/
    protected void registerCustomer(HttpServletRequest request, HttpServletResponse response) throws IOException{

        if(m_AccountControl.registerCustomer(request.getParameterMap())){

            /* write cookie */
            Cookie ckeFirstName = new Cookie("FirstName", URLEncoder.encode(request.getParameter("fst_name"), "UTF-8"));
            Cookie ckeEmail = new Cookie("Email", URLEncoder.encode(request.getParameter("email"), "UTF-8"));
            response.addCookie(ckeFirstName);
            response.addCookie(ckeEmail);
            return;
        }
        /* Update fails, see what is the error */
        response.setContentType("text/xml");
        response.setHeader("Cache-control", "no-cache");

        m_WriteError.setPrintWriter(response.getWriter());
        m_WriteError.doForEach(m_AccountControl.getErrors());
    }
    /*-----------------------------------------------------------------------*/
    protected void getCustomer(HttpServletRequest request, HttpServletResponse response) throws IOException{

        String strCustomerID = request.getParameter("id");

        Customer cust = m_AccountControl.getCustomer(Integer.parseInt(strCustomerID));

        response.setContentType("text/xml");
        response.setHeader("Cache-control", "no-cache");
        PrintWriter pw = response.getWriter();

        if(cust==null){
            /* no customer is returned, see what is the errror */
            m_WriteError.setPrintWriter(pw);
            m_WriteError.doForEach(m_AccountControl.getErrors());
        }
        else{
            /* customer is returned, write xml */
            pw.println("<Employee>");
            pw.println("<CustomerID>" + cust.getCustomerID() + "</CustomerID>");
            pw.println("<RegisteredOn>" + cust.getRegistrationDate() + "</RegisteredOn>");
            pw.println("<UserLevel>" + cust.getUserLevel() + "</UserLevel>");
            pw.println("<Password>" + "XXXXXXXX" + "</Password>");
            
            pw.println("<FirstName>" + cust.getFirstName() + "</FirstName>");
            pw.println("<LastName>" + cust.getLastName() + "</LastName>");
            pw.println("<Email>" + cust.getEmail() + "</Email>");
            pw.println("<Contact>" + cust.getContact() + "</Contact>");
            pw.println("<DOB>" + DateFormat.format(cust.getDOB()) + "</DOB>");
            
            pw.println("<Country>" + cust.getCountry() + "</Country>");
            pw.println("<City>" + cust.getCity() + "</City>");
            pw.println("<State>" + cust.getState() + "</State>");
            pw.println("<AddressLine1>" + cust.getAddressLine1() + "</AddressLine1>");
            pw.println("<AddressLine2>" + cust.getAddressLine2() + "</AddressLine2>");
            pw.println("<PostalCode>" + cust.getPostalCode() + "</PostalCode>");

            pw.println("<CreditCardNumber>" + cust.getCreditCardNumber() + "</CreditCardNumber>");
            pw.println("<CreditCardCVV>" + cust.getCreditCardCVV() + "</CreditCardCVV>");
            pw.println("<CreditCardType>" + cust.getCreditCardType() + "</CreditCardType>");
            pw.println("<CreditCardYear>" + DateFormat.year(cust.getCreditCardExpiry()) + "</CreditCardYear>");
            pw.println("<CreditCardMonth>" + DateFormat.month(cust.getCreditCardExpiry()) + "</CreditCardMonth>");
            pw.println("<CreditCardCVV>" + cust.getCreditCardCVV() + "</CreditCardCVV>");
            pw.println("<CreditCardHolder>" + cust.getCreditCardHolder() + "</CreditCardHolder>");

            pw.println("</Employee>");
           // pw.println("<IsActive>" +  cust.isActive() + "</IsActive>");
        }
        pw.close();
    }
    /*-----------------------------------------------------------------------*/
    protected void updateCustomer(HttpServletRequest request, HttpServletResponse response) throws IOException{
  
        if(m_AccountControl.updateCustomer(request.getParameterMap())){
            /* update cookie */
            Cookie ckeFirstName = new Cookie("FirstName", URLEncoder.encode(request.getParameter("fst_name"), "UTF-8"));
            response.addCookie(ckeFirstName);
            return;
        }

        /* Update fails, see what is the error */
        response.setContentType("text/xml");
        response.setHeader("Cache-control", "no-cache");

        m_WriteError.setPrintWriter(response.getWriter());
        m_WriteError.doForEach(m_AccountControl.getErrors());
    }
    /*-----------------------------------------------------------------------*/
    protected void validateEmail(HttpServletRequest request, HttpServletResponse response) throws IOException{

        String strEmail = request.getParameter("email");
        String strCustomerID = request.getParameter("cust_id");

         m_AccountControl.clearErrors();

        if(strCustomerID.length()==0){ // to handle registration
            if(m_AccountControl.validateEmail(strEmail))
                return;
        }
        else{ // to handle profile updating
            int iCustomerID = Integer.parseInt(request.getParameter("cust_id"));
            if(m_AccountControl.validateEmail(iCustomerID, strEmail))
                return;
        }
        /* validation failed, see what is the error */
        response.setContentType("text/xml");
        response.setHeader("Cache-control", "no-cache");

        m_WriteError.setPrintWriter(response.getWriter());
        m_WriteError.doForEach(m_AccountControl.getErrors());
    }
    /*-----------------------------------------------------------------------*/
    protected void validateContact(HttpServletRequest request, HttpServletResponse response) throws IOException{

        String strContact = request.getParameter("contact");
       
        m_AccountControl.clearErrors();
        if(m_AccountControl.validateContact(strContact)) return;

        /* validation failed, see what is the error */
        response.setContentType("text/xml");
        response.setHeader("Cache-control", "no-cache");

        m_WriteError.setPrintWriter(response.getWriter());
        m_WriteError.doForEach(m_AccountControl.getErrors());
    }
    /*-----------------------------------------------------------------------*/
    protected void validateCreditCardIssuer(HttpServletRequest request, HttpServletResponse response) throws IOException{

        String strCreditCardNumber = request.getParameter("cc_num");
        int iCreditCardType = Integer.parseInt(request.getParameter("cc_type"));

        m_AccountControl.clearErrors();
        if(m_AccountControl.validateCreditCardIssuer(strCreditCardNumber, iCreditCardType))
            return;

        /* validation failed, see what is the error */
        response.setContentType("text/xml");
        response.setHeader("Cache-control", "no-cache");

        m_WriteError.setPrintWriter(response.getWriter());
        m_WriteError.doForEach(m_AccountControl.getErrors());
    }
    /*-----------------------------------------------------------------------*/
    protected void validateCreditCardNumber(HttpServletRequest request, HttpServletResponse response) throws IOException{

        String strCreditCardNumber = request.getParameter("cc_num");

        m_AccountControl.clearErrors();
        if(m_AccountControl.validateCreditCardNumber(strCreditCardNumber))
            return;

        /* validation failed, see what is the error */
        response.setContentType("text/xml");
        response.setHeader("Cache-control", "no-cache");

        m_WriteError.setPrintWriter(response.getWriter());
        m_WriteError.doForEach(m_AccountControl.getErrors());
    }
    /*-----------------------------------------------------------------------*/
    protected void validateCreditCardExpiry(HttpServletRequest request, HttpServletResponse response) throws IOException{

        String strYear = request.getParameter("cc_yr");
        String strMonth = request.getParameter("cc_mth");

        m_AccountControl.clearErrors();
        if(m_AccountControl.validateCreditCardExpiry(strMonth, strYear))
            return;

        /* validation failed, see what is the error */
        response.setContentType("text/xml");
        response.setHeader("Cache-control", "no-cache");

        m_WriteError.setPrintWriter(response.getWriter());
        m_WriteError.doForEach(m_AccountControl.getErrors());
    }
    /*-----------------------------------------------------------------------*/
    protected void validateLastName(HttpServletRequest request, HttpServletResponse response) throws IOException{

        String strLastName = request.getParameter("lst_name");
        m_AccountControl.clearErrors();
        if(m_AccountControl.validateNames(null, strLastName)) return;

        /* validation failed, see what is the error */
        response.setContentType("text/xml");
        response.setHeader("Cache-control", "no-cache");

        m_WriteError.setPrintWriter(response.getWriter());
        m_WriteError.doForEach(m_AccountControl.getErrors());
    }
    /*-----------------------------------------------------------------------*/
    protected void validateFirstName(HttpServletRequest request, HttpServletResponse response) throws IOException{

        String strFirstName = request.getParameter("fst_name");
        m_AccountControl.clearErrors();
        if(m_AccountControl.validateNames(strFirstName, null)) return;

        /* validation failed, see what is the error */
        response.setContentType("text/xml");
        response.setHeader("Cache-control", "no-cache");

        m_WriteError.setPrintWriter(response.getWriter());
        m_WriteError.doForEach(m_AccountControl.getErrors());
    }
    /*-----------------------------------------------------------------------*/
    protected void validateDOB(HttpServletRequest request, HttpServletResponse response) throws IOException{

        String strYear = request.getParameter("dob_yr");
        String strMonth = request.getParameter("dob_mth");
        String strDay = request.getParameter("dob_day");

        m_AccountControl.clearErrors();
        if(m_AccountControl.validateDOB(strYear, strMonth, strDay)) return;

        /* validation failed, see what is the error */
        response.setContentType("text/xml");
        response.setHeader("Cache-control", "no-cache");

        m_WriteError.setPrintWriter(response.getWriter());
        m_WriteError.doForEach(m_AccountControl.getErrors());
    }
    /*-----------------------------------------------------------------------*/
    protected void validateRetypePassword(HttpServletRequest request, HttpServletResponse response) throws IOException{

        String strPassword = request.getParameter("new_pw");
        String strRetype = request.getParameter("retype_pw");

        m_AccountControl.clearErrors();
        if(m_AccountControl.validateRetypePassword(strPassword, strRetype))
            return;

        /* some error occured, see what is it */
        response.setContentType("text/xml");
        response.setHeader("Cache-control", "no-cache");

        m_WriteError.setPrintWriter(response.getWriter());
        m_WriteError.doForEach(m_AccountControl.getErrors());
    }
    /*-----------------------------------------------------------------------*/
    protected void changePassword(HttpServletRequest request, HttpServletResponse response) throws IOException{

        String strPassword = request.getParameter("new_pw");
        String strRetype = request.getParameter("retype_pw");
        int iCustomerID = Integer.parseInt(request.getParameter(("cust_id")));

        if(m_AccountControl.changePassword(strPassword, strRetype, iCustomerID))
            return;

        response.setContentType("text/xml");
        response.setHeader("Cache-control", "no-cache");
        
        m_WriteError.setPrintWriter(response.getWriter());
        m_WriteError.doForEach(m_AccountControl.getErrors());
    }
    /*-----------------------------------------------------------------------*/
    protected void getPasswordStrength(HttpServletRequest request, HttpServletResponse response) throws IOException{

        String strPassword = request.getParameter("pw");
        int iStrength = m_AccountControl.getPasswordStrength(strPassword);

        response.setContentType("text/xml");
        response.setHeader("Cache-control", "no-cache");
        PrintWriter pw = response.getWriter();
        
        pw.println("<Strength>" + iStrength + "</Strength>");
        pw.close();
    }
    /*-----------------------------------------------------------------------*/
    protected void changeCreditCard(HttpServletRequest request, HttpServletResponse response) throws IOException{

        String strCreditCardNumber = request.getParameter("cc_num");
        int strCreditCardType = Integer.parseInt(request.getParameter("cc_type"));
        int iCustomerID = Integer.parseInt(request.getParameter(("cust_id")));

        response.setContentType("text/xml");
        response.setHeader("Cache-control", "no-cache");
        PrintWriter pw = response.getWriter();

        if(m_AccountControl.changeCreditCard(strCreditCardNumber, strCreditCardType, iCustomerID)){       
            pw.println("<CreditCard>");
            pw.println("<CreditCardNumber>" + strCreditCardNumber + "</CreditCardNumber>");
            pw.println("<CreditCardType>" + strCreditCardType + "</CreditCardType>");
            pw.println("</CreditCard>");
            pw.close();
        }else{
            m_WriteError.setPrintWriter(pw);
            m_WriteError.doForEach(m_AccountControl.getErrors());
        }
    }
}
